import time
from base.day12.wangzhe import os_tool as tool

from selenium import webdriver

def login():
    # 1.创建浏览器对象 - 此时浏览器打开
    b = webdriver.Chrome()
    b.get("https://passport.jd.com/uc/login")
    time.sleep(10)
    # 点击短信登录的选项
    # b.find_element_by_xpath('//div[@id="sms-login"]').click()
    # phone_num = input("请输入登录的手机号: ")
    # # 定位到手机号输入框
    # b.find_element_by_xpath('//input[@id="mobile-number"]').send_keys(phone_num)
    # # 定位获取验证码按钮
    # b.find_element_by_xpath('//button[@id="send-sms-code-btn"]').click()
    # # 滑动验证【手动完成】
    # yzm = input("请输入您收到的验证码: ")
    # b.find_element_by_xpath('//input[@id="sms-code"]').send_keys(yzm)
    # # 点击登录按钮
    # b.find_element_by_xpath('//button[@id="sms-login-submit"]').click()

    return b


def get_all_data(b,name):
    b.find_element_by_xpath('//input[@id="key"]').send_keys(name)
    b.find_element_by_xpath('//button[@clstag="h|keycount|h|keycount|head|search_a"]').click()

    time.sleep(2) # 加载数据
    # 滑动到底部
    b.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    time.sleep(3)  # 加载数据
    li_list = b.find_elements_by_xpath('//ul[@class="gl-warp clearfix"]/li')
    for li in li_list:
        # class="p-price" 价格
        sell_price = li.find_element_by_xpath('./div/div[@class="p-price"]/strong/i').text

        try:
            jd_price = li.find_element_by_xpath('./div/div[@class="p-price"]/strong/span/em').text
        except:
            jd_price = '无'

        # 商品名字 class="p-name p-name-type-2"
        jd_goods_name = str(li.find_element_by_xpath('./div/div[@class="p-name p-name-type-2"]/a/em').text).replace("\n","").replace(" ","")
        print(f"商品:{jd_goods_name}, 到手价:{sell_price}, 京东价:{jd_price}")

if __name__ == '__main__':

    tool.kill_process("chromedriver.exe")
    browser = login()
    time.sleep(5) # 加载首页数据

    goods_name = input("请输入要查询的内容：")
    get_all_data(browser,goods_name)
    time.sleep(100)


    browser.quit()